package design.patterns.state;

import design.patterns.observer.Subject;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Observer;

/**
 * Created with IntelliJ IDEA.
 * User: nuno-rafael-figueiredo
 * Date: 04-03-2014
 * Time: 14:06
 */
public class State {
    private final String name;

    public State(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }

    public static class Context extends Subject {
        private static final State CREATED = new State("created");

        private final Map<State, Subject> subjectMap = new LinkedHashMap<>();

        private State state;

        public Context() {
            this.state = CREATED;
        }

        public State getState() {
            return state;
        }

        protected void setState(State state) {
            setState(state, null);
        }

        protected void setState(State state, Object arg) {
            this.state = state;
            getSubject(state).setChangedAndNotifyObservers(arg);
            setChanged();
            notifyObservers(state);
        }

        public Context on(State state, Observer observer) {
            getSubject(state).addObserver(observer);
            return this;
        }

        private Subject getSubject(State state) {
            if (!subjectMap.containsKey(state))
                subjectMap.put(state, new Subject());

            return subjectMap.get(state);
        }
    }
}
